//
//  YLMonthlyBillCalendarController.m
//  YLFinanceService
//
//  Created by she1323 on 2017/9/26.
//  Copyright © 2017年 she1323. All rights reserved.
//  月账单日历

#import "YLMonthlyBillCalendarController.h"
#import "JTCalendar.h"
#import "YLGlobeHeader.h"
#import "YLMonthlyBillCalendarCell.h"
#import "YLMonthlyBillCalendarViewModel.h"
#import "YLMonthlyBillCalendarModel.h"
#import "YLMonthlyBillCalendarListModel.h"
#import <MJRefresh.h>
@interface YLMonthlyBillCalendarController ()<JTCalendarDelegate, UITableViewDelegate, UITableViewDataSource>
{
    NSMutableDictionary *_eventsByDate;
    
//    NSMutableArray *_datesSelected;
    BOOL _selectionMode;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewHeight;

// 页码
@property (nonatomic, assign) NSInteger index;
// 当前日期
@property (nonatomic, strong) NSString *currtentDate;

@property (strong, nonatomic) JTCalendarManager *calendarManager;
@property (weak, nonatomic) IBOutlet JTHorizontalCalendarView *calendarContentView;
@property (weak, nonatomic) IBOutlet JTCalendarMenuView *calendarMenuView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) YLMonthlyBillCalendarViewModel *viewModel;

@end

@implementation YLMonthlyBillCalendarController


- (YLMonthlyBillCalendarViewModel *)viewModel
{
    if (!_viewModel) {
        _viewModel = [[YLMonthlyBillCalendarViewModel alloc] init];
    }
    return _viewModel;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    __weak typeof(self) weakSelf = self;
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([YLMonthlyBillCalendarCell class]) bundle:nil] forCellReuseIdentifier:[YLMonthlyBillCalendarCell cellID]];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.index = 1;
        [weakSelf loadList:weakSelf.calendarContentView.date];
        
    }];
    
    self.tableViewHeight.constant = 0;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.index ++;
        [weakSelf loadList:weakSelf.calendarContentView.date];
    }];
    
    
    self.view.backgroundColor = YLColorA(0, 0, 0, 0.3);
    
    _calendarManager = [JTCalendarManager new];
    _calendarManager.delegate = self;
    
    [self createRandomEvents];
    
    _calendarManager.settings.weekDayFormat = JTCalendarWeekDayFormatSingle;
    
    [_calendarManager setMenuView:_calendarMenuView];
    _calendarContentView.backgroundColor = [UIColor whiteColor];
    _calendarContentView.delegate = self;
    [_calendarManager setContentView:_calendarContentView];
    [_calendarManager setDate:[NSDate date]];
    
    
    _selectionMode = NO;
    
    [self loadData:_calendarContentView.date];
    [self.tableView.mj_header beginRefreshing];
    
    [self.viewModel.wh_noMoreDataSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
    }];
    
    [self.viewModel.wh_loadDataErrorSubject subscribeNext:^(id  _Nullable x) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
    }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
 
    if (scrollView == _tableView) {
        return;
    }
    [self loadData:_calendarContentView.date];
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadList:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowDateStr = [dateFormatter stringFromDate:date];
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:3];
   // params[@""]
    params[@"PageIndex"] = @(_index);
    params[@"TimeIndex"] = nowDateStr;
    
    __weak typeof(self) weakSelf = self;
    [[self.viewModel.listCommand execute:params] subscribeNext:^(id  _Nullable x) {
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];
        
    }];
}

- (void)loadData:(NSDate *)date
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *nowDateStr = [dateFormatter stringFromDate:date];
    __weak typeof(self) weakSelf = self;
    [[self.viewModel.requestCommand execute:nowDateStr] subscribeNext:^(id  _Nullable x) {
        [weakSelf.calendarManager reload];
    }];
    
    
}

#pragma mark - Buttons callback

- (IBAction)didSelectionModeTouch
{
    _selectionMode = !_selectionMode;
    
    if(_selectionMode){
      //  [_datesSelected removeAllObjects];
        [self.viewModel.dates removeAllObjects];
        [_calendarManager reload];
    }
}

#pragma mark - CalendarManager delegate

- (void)calendar:(JTCalendarManager *)calendar prepareDayView:(JTCalendarDayView *)dayView
{
    // Today
    dayView.whiteView.hidden = YES;
    // Selected date
    if([[self isInDateSelected:dayView.date] isKindOfClass:[YLMonthlyBillCalendarModel class]]){
        dayView.circleView.hidden = NO;
         dayView.circleView.backgroundColor = [UIColor redColor];
        dayView.dotView.backgroundColor = [UIColor whiteColor];
        dayView.textLabel.textColor = [UIColor whiteColor];
        YLMonthlyBillCalendarModel *model = [self isInDateSelected:dayView.date];
        if (model.status == 0) {
            dayView.circleView.backgroundColor = [UIColor orangeColor];
        } else if (model.status == 1) {
            dayView.circleView.backgroundColor = YLLOrgColor;
        } else {
            dayView.circleView.backgroundColor = YLMainColor;
        }
        
    }
    // Other month
    else if(![_calendarManager.dateHelper date:_calendarContentView.date isTheSameMonthThan:dayView.date]){
         dayView.circleView.hidden = YES;
        dayView.signView.hidden = YES;
        //  dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor lightGrayColor];
    }
    // Another day of the current month
    else{
          dayView.circleView.hidden = YES;
        dayView.signView.hidden = YES;
        //  dayView.dotView.backgroundColor = [UIColor redColor];
        dayView.textLabel.textColor = [UIColor blackColor];
    }
    
    if([self haveEventForDay:dayView.date]){
        dayView.dotView.hidden = NO;
    }
    else{
        dayView.dotView.hidden = YES;
    }
    
}

- (id)isInDateSelected:(NSDate *)date
{
    for(YLMonthlyBillCalendarModel *dateSelected in self.viewModel.dates){
        if([_calendarManager.dateHelper date:dateSelected.date isTheSameDayThan:date]){
            return dateSelected;
        }
    }
    return nil;
}


#pragma mark - Fake data

#pragma mark - Views customization

- (UIView *)calendarBuildMenuItemView:(JTCalendarManager *)calendar
{
    UILabel *label = [UILabel new];
    
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Avenir-Medium" size:16];
    
    return label;
}

- (void)calendar:(JTCalendarManager *)calendar prepareMenuItemView:(UILabel *)menuItemView date:(NSDate *)date
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"yyyy年MMMM";
        
        dateFormatter.locale = _calendarManager.dateHelper.calendar.locale;
        dateFormatter.timeZone = _calendarManager.dateHelper.calendar.timeZone;
    }
    
    menuItemView.text = [dateFormatter stringFromDate:date];
}

- (UIView<JTCalendarWeekDay> *)calendarBuildWeekDayView:(JTCalendarManager *)calendar
{
    JTCalendarWeekDayView *view = [JTCalendarWeekDayView new];
    
    for(UILabel *label in view.dayViews){
        label.textColor = [UIColor blackColor];
        label.font = [UIFont fontWithName:@"Avenir-Light" size:14];
    }
    
    return view;
}

- (UIView<JTCalendarDay> *)calendarBuildDayView:(JTCalendarManager *)calendar
{
    JTCalendarDayView *view = [JTCalendarDayView new];
    
    view.textLabel.font = [UIFont fontWithName:@"Avenir-Light" size:13];
    
    view.circleRatio = .8;
    view.dotRatio = 1. / .9;
    
    return view;
}

#pragma mark - Fake data

// Used only to have a key for _eventsByDate
- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }
    
    return dateFormatter;
}

- (BOOL)haveEventForDay:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    
    if(_eventsByDate[key] && [_eventsByDate[key] count] > 0){
        return YES;
    }
    
    return NO;
    
}

- (void)createRandomEvents
{
    _eventsByDate = [NSMutableDictionary new];
    
    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];
        
        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];
        
        if(!_eventsByDate[key]){
            _eventsByDate[key] = [NSMutableArray new];
        }
        
        [_eventsByDate[key] addObject:randomDate];
    }
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSInteger count = self.viewModel.lists.count > 4 ? 4 : self.viewModel.lists.count;
    
    _tableViewHeight.constant = count * 44;
    
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.viewModel.lists.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YLMonthlyBillCalendarCell *cell = [tableView dequeueReusableCellWithIdentifier:[YLMonthlyBillCalendarCell cellID] forIndexPath:indexPath];
    cell.model = self.viewModel.lists[indexPath.row];
    return cell;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    self.view.hidden = YES;
    _calendarMenuView = nil;
    _calendarContentView = nil;
    _calendarManager = nil;
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
    
}

@end
